package com.ossean.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;

@Component("uRLAvailability")
public class URLAvailability {
	private static URL url;
	private static HttpURLConnection con;
	private static int state = -1;

	/**
	 * 功能：检测当前URL是否可连接或是否有效, 描述：最多连接网络 5 次, 如果 5 次都不成功，视为该地址不可用
	 * 
	 * @param urlStr
	 * 指定URL网络地址
	 * @return URL
	 */
	public synchronized static boolean isConnect2(String urlStr) {
		if (urlStr == null || urlStr.length() <= 0) {
			return false;
		}
		try {
			url = new URL(urlStr);
			con = (HttpURLConnection) url.openConnection();
			state = con.getResponseCode();
			if (state == -1) {
				//System.out.println("URL不可用！");
				return false;
			}
			return true;
		} catch (Exception ex) {
			return false;
		}
	}
	
	public static boolean isConnect(String urlStr) {  
	    URL url;  
	    try {  
	         url = new URL(urlStr);  
	         InputStream in = url.openStream();  
	         return true;  
	    } catch (Exception e1) {  
	         //System.out.println("连接打不开!");  
	         return false;  
	    }  
	}
	public static boolean isRightUrlByRegex(String urlStr){
		Pattern p = Pattern.compile("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?",Pattern.CASE_INSENSITIVE );
		Matcher m = p.matcher(urlStr);    
        if(m.find()){  
            //System.out.println(m.group());
            return true;
        }else
        	return false;
	}

	public static void main(String[] args) {
		//URLAvailability u = new URLAvailability();
		//System.out.println(isConnect2("http://www.oschina.nethttps://market.aliyun.com/software?spm=5176.1846502.0.0.CpQnwc"));
		System.out.println(isRightUrlByRegex("https://www.openhub.net/p/tesseracthttp://abc.com"));
		//System.out.println(isConnect("http://www.freecode.com/projects/pdfsam"));
	}

}
